package com.simtop.car.controller;

import com.simtop.car.pojo.*;
import com.simtop.car.service.ExcelService;
import com.simtop.car.utils.EmptyUtil;
import com.simtop.car.utils.ExcelUtils;
import com.simtop.car.utils.JwtUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * @Description : TODO用一句话描述此类的作用
 */
@Api(tags = "ExcelDownloadController", description = "Excel 导入下载模板，导出 相关接口")
@RestController
@RequestMapping("/excel")
@CrossOrigin //todo 跨域问题
public class ExcelDownloadController {
    private static final Logger log = LoggerFactory.getLogger(ExcelDownloadController.class);


    @Autowired
    public ExcelService excelService;


    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    /**
     * 单个文件上传
     * @param file
     * @return
     */
    @ApiOperation(value="接口说明",httpMethod="POST",notes="单个文件上传")
    @RequestMapping(value = "/upload",method = RequestMethod.POST)
    public ResponseMsg upload(MultipartFile file,Integer sourceId,HttpServletRequest request) {
        ResponseMsg msg = new ResponseMsg();
        String token = request.getHeader("Authorization");
        String jwt = token.substring(token.lastIndexOf(" ")+1);
        User u = JwtUtil.unsign(jwt,User.class);
        if(u == null){
            msg.setMsg("token无效");
            msg.setResult(false);
            return msg;
        }
        try {
            if (file.isEmpty()) {
                msg.setMsg("文件为空");
                msg.setResult(false);
                return msg;
            }
            // 获取文件名
            String fileName = file.getOriginalFilename();
            log.info("上传的文件名为：" + fileName);
            // 获取文件的后缀名
            String suffixName = fileName.substring(fileName.lastIndexOf("."));
            log.info("文件的后缀名为：" + suffixName);
            //创建一个临时文件，用于暂时存放
            File tmpFile = File.createTempFile("tmp", null);
            //将MultipartFile 转换为 File 临时文件
            file.transferTo(tmpFile);
            //将临时文件转为输入流
            InputStream inputStream = new FileInputStream(tmpFile);
            if(sourceId==1){
                List<Object> objectList=ExcelUtils.readExcel(inputStream, WeiBo.class);
                if(objectList==null){
                    log.info("数据有误");
                    msg.setResult(false);
                    msg.setMsg("数据有误，上传失败");
                    return msg;
                }
                else if(EmptyUtil.isEmpty(objectList)){
                    log.info("空");
                    msg.setResult(false);
                    msg.setMsg("数据为空");
                    return msg;
                }else {
                    List<WeiBo> weiBoList=new ArrayList<>();
                    for (int i = 0; i <objectList.size(); i++) {
                        WeiBo weiBo= (WeiBo) objectList.get(i);
                        weiBo.setWeiboId(sourceId);
                        weiBo.setUserId(u.getId());
                        String blogArticle=weiBo.getBlogArticle();
                        String username=weiBo.getUsername();
                        if (username != null && username.length() > 0) {
                            weiBo.setUsername(username.replaceAll("[\ud800\udc00-\udbff\udfff\ud800-\udfff]", ""));
                        } else {
                            weiBo.setUsername(username);
                        }
                        if (blogArticle != null && blogArticle.length() > 0) {
                            weiBo.setBlogArticle(blogArticle.replaceAll("[\ud800\udc00-\udbff\udfff\ud800-\udfff]", ""));
                        } else {
                            weiBo.setBlogArticle(blogArticle);
                        }
                        weiBoList.add(weiBo);
                        if((i+1)%500==0){
                            excelService.exportWeibo(weiBoList);
                            weiBoList.clear();
                        }
                    }
                    if(weiBoList.size()!=0){
                        excelService.exportWeibo(weiBoList);
                    }
                    String keys = "weiBoCountNums*";
                    Set keysSet = redisTemplate.keys(keys);
                    redisTemplate.delete(keysSet);
                    //上传完成 删除临时文件
                    tmpFile.delete();
                }
            }
            if(sourceId==2){
                List<Object> objectList=ExcelUtils.readExcel(inputStream, WeChat.class);
                if(objectList==null){
                    log.info("数据有误");
                    msg.setResult(false);
                    msg.setMsg("数据有误，上传失败");
                    return msg;
                }
                else if(EmptyUtil.isEmpty(objectList)){
                    log.info("空");
                    msg.setResult(false);
                    msg.setMsg("数据为空");
                    return msg;
                }else{
                    List<WeChat> weChatList=new ArrayList<>();
                    for (int i = 0; i <objectList.size(); i++) {
                        WeChat weChat= (WeChat) objectList.get(i);
                        weChat.setWechatId(sourceId);
                        weChat.setUserId(u.getId());
                        weChatList.add(weChat);
                        if((i+1)%500==0){
                            excelService.exportWeChat(weChatList);
                            weChatList.clear();
                        }
                    }
                    if(weChatList.size()!=0){
                        excelService.exportWeChat(weChatList);
                    }
                    String keys = "weiXinCountNums*";
                    Set keysSet = redisTemplate.keys(keys);
                    redisTemplate.delete(keysSet);
                    //上传完成 删除临时文件
                    tmpFile.delete();
                }
            }
            if(sourceId==3){
                List<Object> objectList=ExcelUtils.readExcel(inputStream, News.class);
                if(objectList==null){
                    log.info("数据有误");
                    msg.setResult(false);
                    msg.setMsg("数据有误，上传失败");
                    return msg;
                }
                else if(EmptyUtil.isEmpty(objectList)){
                    log.info("空");
                    msg.setResult(false);
                    msg.setMsg("数据为空");
                    return msg;
                }else{
                    List<News> newsList=new ArrayList<>();
                    for (int i = 0; i <objectList.size(); i++) {
                        News news= (News) objectList.get(i);
                        news.setNewsSourceId(sourceId);
                        news.setUserId(u.getId());
                        newsList.add(news);
                        if((i+1)%500==0){
                            excelService.exportNews(newsList);
                            newsList.clear();
                        }
                    }
                    if(newsList.size()!=0){
                        excelService.exportNews(newsList);
                    }
                    String keys = "newsCountNums*";
                    Set keysSet = redisTemplate.keys(keys);
                    redisTemplate.delete(keysSet);
                    //上传完成 删除临时文件
                    tmpFile.delete();
                }
            }
            if(sourceId==4){
                List<Object> objectList=ExcelUtils.readExcel(inputStream, Recruitment.class);
                if(objectList==null){
                    log.info("数据有误");
                    msg.setResult(false);
                    msg.setMsg("数据有误，上传失败");
                    return msg;
                }
                else if(EmptyUtil.isEmpty(objectList)){
                    log.info("空");
                    msg.setResult(false);
                    msg.setMsg("数据为空");
                    return msg;
                }else{
                    List<Recruitment> recruitmentList=new ArrayList<>();
                    for (int i = 0; i <objectList.size(); i++) {
                        Recruitment recruitment= (Recruitment) objectList.get(i);
                        recruitment.setRecruitmentSourceId(sourceId);
                        recruitment.setUserId(u.getId());
                        String jobDescription=recruitment.getJobDescription();
                        if (jobDescription != null && jobDescription.length() > 0) {
                            recruitment.setJobDescription(jobDescription.replaceAll("[\ud800\udc00-\udbff\udfff\ud800-\udfff]", ""));
                        } else {
                            recruitment.setJobDescription(jobDescription);
                        }
                        recruitmentList.add(recruitment);

                        if((i+1)%500==0){
                            excelService.exportRecruitment(recruitmentList);
                            recruitmentList.clear();
                        }
                    }
                    if(recruitmentList.size()!=0){
                        excelService.exportRecruitment(recruitmentList);
                    }
                    String keys = "recruitmentCountNums*";
                    Set keysSet = redisTemplate.keys(keys);
                    redisTemplate.delete(keysSet);
                    //上传完成 删除临时文件
                    tmpFile.delete();
                }
            }
            if(sourceId==5){
                List<Object> objectList=ExcelUtils.readExcel(inputStream, Patent.class);
                if(objectList==null){
                    log.info("数据有误");
                    msg.setResult(false);
                    msg.setMsg("数据有误，上传失败");
                    return msg;
                }
                else if(EmptyUtil.isEmpty(objectList)){
                    log.info("空");
                    msg.setResult(false);
                    msg.setMsg("数据为空");
                    return msg;
                }else{
                    List<Patent> patentList=new ArrayList<>();
                    for (int i = 0; i <objectList.size(); i++) {
                        Patent patent= (Patent) objectList.get(i);
                        patent.setPatentSourceId(sourceId);
                        patent.setUserId(u.getId());
                        patentList.add(patent);
                        if((i+1)%500==0){
                            excelService.exportPatent(patentList);
                            patentList.clear();
                        }
                    }
                    if(patentList.size()!=0){
                        excelService.exportPatent(patentList);
                    }
                    String keys = "patentCountNums*";
                    Set keysSet = redisTemplate.keys(keys);
                    redisTemplate.delete(keysSet);
                    //上传完成 删除临时文件
                    tmpFile.delete();
                }
            }
            if(sourceId==6){
                List<Object> objectList=ExcelUtils.readExcel(inputStream, CompanyWebsite.class);
                if(objectList==null){
                    log.info("数据有误");
                    msg.setResult(false);
                    msg.setMsg("数据有误，上传失败");
                    return msg;
                }
                else if(EmptyUtil.isEmpty(objectList)){
                    log.info("空");
                    msg.setResult(false);
                    msg.setMsg("数据为空");
                    return msg;
                }else{
                    List<CompanyWebsite> companyWebsiteList=new ArrayList<>();
                    for (int i = 0; i <objectList.size(); i++) {
                        CompanyWebsite companyWebsite= (CompanyWebsite) objectList.get(i);
                        companyWebsite.setCompanyWebsiteSourceId(sourceId);
                        companyWebsite.setUserId(u.getId());
                        companyWebsiteList.add(companyWebsite);
                        if((i+1)%500==0){
                            excelService.exportCompanyWebsite(companyWebsiteList);
                            companyWebsiteList.clear();
                        }
                    }
                    if(companyWebsiteList.size()!=0){
                        excelService.exportCompanyWebsite(companyWebsiteList);
                    }
                    String keys = "companyWebsiteCountNums*";
                    Set keysSet = redisTemplate.keys(keys);
                    redisTemplate.delete(keysSet);
                    //上传完成 删除临时文件
                    tmpFile.delete();
                }
            }
            if(sourceId==7){
                List<Object> objectList=ExcelUtils.readExcel(inputStream, CommunityForum.class);
                if(objectList==null){
                    log.info("数据有误");
                    msg.setResult(false);
                    msg.setMsg("数据有误，上传失败");
                    return msg;
                }
                else if(EmptyUtil.isEmpty(objectList)){
                    log.info("空");
                    msg.setResult(false);
                    msg.setMsg("数据为空");
                    return msg;
                }else{
                    List<CommunityForum> communityForumList=new ArrayList<>();
                    for (int i = 0; i <objectList.size(); i++) {
                        CommunityForum communityForum= (CommunityForum) objectList.get(i);
                        communityForum.setCommunityForumSourceId(sourceId);
                        communityForum.setUserId(u.getId());
                        communityForumList.add(communityForum);
                        if((i+1)%500==0){
                            excelService.exportCommunityForum(communityForumList);
                            communityForumList.clear();
                        }
                    }
                    if(communityForumList.size()!=0){
                        excelService.exportCommunityForum(communityForumList);
                    }
                    String keys = "communityForumCountNums*";
                    Set keysSet = redisTemplate.keys(keys);
                    redisTemplate.delete(keysSet);
                    //上传完成 删除临时文件
                    tmpFile.delete();
                }
            }
            if(sourceId==8){
                List<Object> objectList=ExcelUtils.readExcel(inputStream, CorporateAnnualReports.class);
                if(objectList==null){
                    log.info("数据有误");
                    msg.setResult(false);
                    msg.setMsg("数据有误，上传失败");
                    return msg;
                }
                else if(EmptyUtil.isEmpty(objectList)){
                    log.info("空");
                    msg.setResult(false);
                    msg.setMsg("数据为空");
                    return msg;
                }else{
                    List<CorporateAnnualReports> corporateAnnualReportsList=new ArrayList<>();
                    for (int i = 0; i <objectList.size(); i++) {
                        CorporateAnnualReports corporateAnnualReports= (CorporateAnnualReports) objectList.get(i);
                        corporateAnnualReports.setReportsSourceId(sourceId);
                        corporateAnnualReports.setUserId(u.getId());
                        corporateAnnualReportsList.add(corporateAnnualReports);
                        if((i+1)%500==0){
                            excelService.exportCorporateAnnualReports(corporateAnnualReportsList);
                            corporateAnnualReportsList.clear();
                        }
                    }
                    if(corporateAnnualReportsList.size()!=0){
                        excelService.exportCorporateAnnualReports(corporateAnnualReportsList);
                    }
                    String keys = "corporateAnnualReportsCountNums*";
                    Set keysSet = redisTemplate.keys(keys);
                    redisTemplate.delete(keysSet);
                    //上传完成 删除临时文件
                    tmpFile.delete();
                }
            }
            if(sourceId==9){
                List<Object> objectList=ExcelUtils.readExcel(inputStream, BusinessInformation.class);
                if(objectList==null){
                    log.info("数据有误");
                    msg.setResult(false);
                    msg.setMsg("数据有误，上传失败");
                    return msg;
                }
                else if(EmptyUtil.isEmpty(objectList)){
                    log.info("空");
                    msg.setResult(false);
                    msg.setMsg("数据为空");
                    return msg;
                }else{
                    List<BusinessInformation> businessInformationList=new ArrayList<>();
                    for (int i = 0; i <objectList.size(); i++) {
                        BusinessInformation businessInformation= (BusinessInformation) objectList.get(i);
                        businessInformation.setInformationSourceId(sourceId);
                        businessInformation.setUserId(u.getId());
                        businessInformationList.add(businessInformation);
                        if((i+1)%500==0){
                            excelService.exportBusinessInformation(businessInformationList);
                            businessInformationList.clear();
                        }
                    }
                    if(businessInformationList.size()!=0){
                        excelService.exportBusinessInformation(businessInformationList);
                    }
                    String keys = "businessInformationCountNums*";
                    Set keysSet = redisTemplate.keys(keys);
                    redisTemplate.delete(keysSet);
                    //上传完成 删除临时文件
                    tmpFile.delete();
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        msg.setResult(true);
        msg.setMsg("上传成功");
        return msg;
    }

    /**
     * 下载模板，用于填写导入数据
     * @param request
     * @param response
     */
    @RequestMapping("/downloadExcel")
    public void cooperation(HttpServletRequest request, HttpServletResponse response,Integer sourceId) {
        ServletOutputStream out = null;
        try {
            out = response.getOutputStream();
            response.setContentType("multipart/form-data");
            response.setCharacterEncoding("utf-8");
            String fileName = "";
            switch (sourceId){
                case 1:fileName="微博导入模板";break;
                case 2:fileName="微信导入模板";break;
                case 3:fileName="新闻导入模板";break;
                case 4:fileName="招聘导入模板";break;
                case 5:fileName="专利导入模板";break;
                case 6:fileName="企业官网导入模板";break;
                case 7:fileName="社区论坛导入模板";break;
                case 8:fileName="企业年报导入模板";break;
                case 9:fileName="工商信息导入模板";break;
            }
            response.setHeader("Content-disposition", "attachment;filename="+ URLEncoder.encode(fileName,"UTF-8")+".xlsx");
            switch (sourceId){
                case 1:ExcelUtils.writeExcel(out, WeiBo.class,null);break;
                case 2:ExcelUtils.writeExcel(out, WeChat.class,null);break;
                case 3:ExcelUtils.writeExcel(out, News.class,null);break;
                case 4:ExcelUtils.writeExcel(out, Recruitment.class,null);break;
                case 5:ExcelUtils.writeExcel(out, Patent.class,null);break;
                case 6:ExcelUtils.writeExcel(out, CompanyWebsite.class,null);break;
                case 7:ExcelUtils.writeExcel(out, CommunityForum.class,null);break;
                case 8:ExcelUtils.writeExcel(out, CorporateAnnualReports.class,null);break;
                case 9:ExcelUtils.writeExcel(out, BusinessInformation.class,null);break;
            }
            out.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (out != null){
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @RequestMapping("/downloadExcel2")
    public void cooperation2(HttpServletRequest request, HttpServletResponse response,Integer sourceId) {
        log.info("sourceId"+sourceId);
        //  @RequestBody Integer sourceId
        JSONObject jsonObj = new JSONObject(sourceId);
        Integer downSourceId=sourceId;
        ServletOutputStream out = null;
        try {
            out = response.getOutputStream();
            response.setContentType("multipart/form-data");
            response.setCharacterEncoding("utf-8");
            String fileName = "";
            switch (downSourceId){
                case 1:fileName="微博导入模板";break;
                case 2:fileName="微信导入模板";break;
                case 3:fileName="新闻导入模板";break;
                case 4:fileName="招聘导入模板";break;
                case 5:fileName="专利导入模板";break;
                case 6:fileName="企业官网导入模板";break;
                case 7:fileName="社区论坛导入模板";break;
                case 8:fileName="企业年报导入模板";break;
                case 9:fileName="工商信息导入模板";break;
            }
            response.setHeader("Content-disposition", "attachment;filename="+ URLEncoder.encode(fileName,"UTF-8")+".xlsx");
            switch (downSourceId){
                case 1:ExcelUtils.writeExcel(out, WeiBo.class,null);break;
                case 2:ExcelUtils.writeExcel(out, WeChat.class,null);break;
                case 3:ExcelUtils.writeExcel(out, News.class,null);break;
                case 4:ExcelUtils.writeExcel(out, Recruitment.class,null);break;
                case 5:ExcelUtils.writeExcel(out, Patent.class,null);break;
                case 6:ExcelUtils.writeExcel(out, CompanyWebsite.class,null);break;
                case 7:ExcelUtils.writeExcel(out, CommunityForum.class,null);break;
                case 8:ExcelUtils.writeExcel(out, CorporateAnnualReports.class,null);break;
                case 9:ExcelUtils.writeExcel(out, BusinessInformation.class,null);break;
            }
            out.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (out != null){
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
